package com.aviccxzx.smarthome.UserModule;

import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aviccxzx.smarthome.R;
import com.aviccxzx.smarthome.base.GosUserModuleBaseActivity;
import com.aviccxzx.smarthome.entity.CamBound;
import com.aviccxzx.smarthome.entity.CamExit;
import com.aviccxzx.smarthome.netutil.app.App;
import com.aviccxzx.smarthome.service.RetrofitHelper;
import com.aviccxzx.smarthome.service.RetrofitService;
import com.aviccxzx.smarthome.video.HmacSHA1Signature;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import okhttp3.Interceptor;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by joey on 2016/10/25.
 */
public class InputYstActivity extends GosUserModuleBaseActivity implements View.OnClickListener {

    EditText content;//定义一个文本输入框
    TextView hasnum;// 用来显示剩余字数
    int num = 10;//限制的最大字数
    EditText ystno_tv;

    private Dialog dialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            setContentView(R.layout.enter_ystno_lay_v19);
        } else {
        }
        ((TextView) findViewById(R.id.title_tv)).setText("输入ID号");
        findViewById(R.id.ll_title_left_view).setOnClickListener(this);
        findViewById(R.id.yst_input).setOnClickListener(this);
        ystno_tv = (EditText) findViewById(R.id.ystno_tv);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_title_left_view:
                finish();
                break;
            case R.id.yst_input:
                String mactv = ystno_tv.getText().toString().trim();
                String cam = "[A-Za-z]\\d{8}";
                String cam1 = "[A-Za-z]\\d{9}";
                if (!TextUtils.isEmpty(mactv)&&mactv.matches(cam)||!TextUtils.isEmpty(mactv)&&mactv.matches(cam1)) {
                    CheckDevExist(mactv);
                } else {
                    App.getApp().showToast("请输入摄像机底部的ID号");
                }
                break;
        }
    }

    /**
     * 获取摄像头有效性
     */
    public void CheckDevExist(final String ystno) {
        progressDialog.show();
        final String url = "http://avci.soovvi.com/CheckDevExist";
        //String host = "xwdev.soovvi.com";
        final String host = "182.92.201.219";
        String accessKeyId = "zhonghangdainzi";
        String accessKeySecret = "123456789";
        final String yst = ystno;

        Calendar cd = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("EEE d MMM yyyy HH:mm:ss 'GMT'", Locale.US);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT")); // 设置时区为GMT
        final String gmtDate = sdf.format(cd.getTime());

        String signature = HmacSHA1Signature.computeSignature(accessKeySecret, yst + "\n" + gmtDate + "\n");
        final String authorization = accessKeyId + ":" + signature;

        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", authorization);
        headers.put("Date", gmtDate);
        headers.put("Host", host);
        headers.put("Yst", yst);
        Map<String, String> params = new HashMap<>();

        //添加请求头拦截器
        Interceptor addHeader = new Interceptor() {
            @Override
            public okhttp3.Response intercept(Chain chain) throws IOException {
                Request request = new Request.Builder()
                        .url(url)
                        .addHeader("content-type", "application/json")
                        .addHeader("Authorization", authorization)
                        .addHeader("Date", gmtDate)
                        .addHeader("Yst", yst)
                        .build();
                return chain.proceed(request);
            }
        };

        RetrofitService service = RetrofitHelper.getInstance(this).getStatusServer(addHeader);
        Call<CamExit> call = service.CheckDevExist(url);
        call.enqueue(new Callback<CamExit>() {
            @Override
            public void onResponse(Call<CamExit> call, Response<CamExit> response) {
                int online = response.body().getRoot().getExist();
                if (online == 0) {
                    //无效设备
                    App.getApp().showToast(ystno+"设备无效");
                    progressDialog.dismiss();
                } else {
                    //有效设备
                    //1.查询设备是否在线 在线就直接走机智云绑定，离线走配网流程

                    //2.调用机智云接口查询该摄像头是否被添加了,如果被添加则提示无法添加
                    camisBound(ystno);
                }
            }

            @Override
            public void onFailure(Call<CamExit> call, Throwable t) {
//                App.getApp().showToast("状态查询失败");
                progressDialog.dismiss();
            }
        });
    }

    public void camisBound(final String yst) {
        //        showProgressDialog("查询中...");
        RetrofitService service = RetrofitHelper.getInstance(this).getServer();
        Call<CamBound> call = service.camisBound(yst);
        call.enqueue(new Callback<CamBound>() {
            @Override
            public void onResponse(Call<CamBound> call, Response<CamBound> response) {
                int code = response.body().getCode();
                if (code == 200) {
                    //已经被绑定，提示用户已经被绑定
                    App.getApp().showToast("设备" + yst + "已经被绑定");
                    progressDialog.dismiss();
                } else if (code == 201) {
                    //设备在线状态
//                    getCamStatus(yst);
                    //修改为每次添加摄像机时都要走绑定流程
                    Intent intent = new Intent(InputYstActivity.this, VideoResetActivity.class);
                    intent.putExtra("yst", yst);
                    startActivity(intent);
                    progressDialog.dismiss();
                }
            }

            @Override
            public void onFailure(Call<CamBound> call, Throwable t) {
                App.getApp().showToast("查询失败，请稍后重试");
                progressDialog.dismiss();
            }
        });
    }
}
